import dayjs from "dayjs";
import { useApptore } from "../stores/app";
import { notification } from "ant-design-vue";
import {
  closeLuckyBigPop,
  openLuckyBigTool,
  popUpGoodsPop,
  releaseLuckyBigByIndex,
  sendMessageAndTop,
} from "./operationUtils/dy";
import { xhsPopUpGoodsPop, xhsSendMessage } from "./operationUtils/xhs";
import { createAjaxHookConfig } from "./operationUtils/ajax-hook-config";
import { parseUrlParams } from "./utils";

export function useExecute() {
  createAjaxHookConfig({
    onResponse: (response: any, handler: any) => {
      let resUrl = response.config.url;
      let roomUrl = "api/anchor/livepc/room_stats";
      let searchUrl = "api/buyin/marketing/draw/search";
      let releaseUrl = "api/buyin/marketing/draw/launch";
      // 获取累计数据的接口
      if (resUrl.includes(roomUrl)) {
        let res = JSON.parse(response.response);
        console.log(res, roomUrl);
        currentUserCnt = res.data.current_user_cnt;
        // 查询福袋列表的接口
      } else if (resUrl.includes(searchUrl)) {
        let parse = parseUrlParams(resUrl);
        let res = JSON.parse(response.response);
        console.log(
          luckyBagStepIndex,
          parse["act_status"],
          res,
          "luckyBagStepIndex"
        );

        // 当前福袋待开始的请求参数 parse["act_status"] == 1
        if (parse["act_status"] == 1 && isObtainStatus) {
          setTimeout(() => {
            if (luckyBagStepIndex != 1) return;
            // activity_id 活动id
            // act_status 1活动未开始 2活动进行中 3活动已结束 5活动异常
            let luckyBags: any[] = res.data.draws;
            console.log(res.data.draws, "res.data.draws");

            if (luckyBags.length == 0) {
              isObtainStatus = false;
              closeLuckyBigPop();
            } else {
              // 所有可以发布的福袋Id组成的字符串
              let luckyBagIds: string[] =
                luckyBagConfigTemplate.luckyBagIds.split("\n");
              let luckyIndex = luckyBags.findIndex((item) => {
                let curId = luckyBagIds.find(
                  (it) => item.activity_id == it && item.act_status == 1
                );
                return curId;
              });

              // 找到了绑定的福袋Id，点击开发发布福袋
              if (luckyIndex != -1) {
                console.log(luckyIndex, "luckyIndex");
                releaseLuckyBigByIndex(luckyIndex);
                luckyBagStepIndex = 2;
              } else {
                // 没找到了绑定的福袋Id，取消任务，重置任务步骤
                isObtainStatus = false;
                luckyBagStepIndex = 0;
                closeLuckyBigPop();
              }
            }
          }, 1000);
          // 当前福袋进行中的请求参数 parse["act_status"] == 2
        } else if (
          parse["act_status"] == 2 &&
          luckyBagStepIndex == 1 &&
          isObtainStatus
        ) {
          // activity_id 活动id
          // act_status 1活动未开始 2活动进行中 3活动已结束 5活动异常
          let luckyBags: any[] = res.data.draws;
          if (luckyBags.length) {
            luckyBagStepIndex = 0;
          } else {
            closeLuckyBigPop();
          }
        }
      } else if (resUrl.includes(releaseUrl) && luckyBagStepIndex == 2) {
        let parse = parseUrlParams(resUrl);
        let res = JSON.parse(response.response);
        console.log(luckyBagStepIndex, parse, res, "luckyBagStepIndex");
        // 当前已有正在进行中的福袋
        if (res.code == 10000088) {
          luckyBagStepIndex = 0;
          // 当前用户未开播
        } else if (res.code == 10000001) {
          luckyBagStepIndex = 0;
          isObtainStatus = false;
        } else if (res.code == 0) {
          luckyBagReleaseTime = dayjs().unix();
          luckyBagStepIndex = 0;
        }
        closeLuckyBigPop();
      }

      handler.next(response);
    },
  });

  let app = useApptore();
  let checkStatus = false; // 判断推广费是否正在获取中
  let timer: any = null;
  let configTemplate: any[] = [];
  let sendTimes: any[] = []; // 记录上次完成操作的时间
  let startTimeUnix: number | null = null;
  /**
   *  判断福袋是否还有未执行的福袋
   */
  let isObtainStatus = true;
  /**
   *  福袋逻辑执行时间
   */
  let luckyBagExecuteTime = 0;
  /**
   *  福袋发布时间
   */
  let luckyBagReleaseTime = 0;
  /**
   *  发布福袋的步骤逻辑
   * 0默认值
   * 1已点击打开福袋弹框控件
   * 2已点击切换福袋弹框中的福袋列表到全部
   * 3已获取所有福袋状态
   * 4已点击发布福袋
   */
  let luckyBagStepIndex = 0;
  let currentUserCnt = 0; // 实时在线用户数量
  let luckyBagConfigTemplate: any = null;

  init();

  function init() {
    if (!app.isExecuteConfigId) return;
    let configData = app.configFrom.find(
      (item) => item.id === app.isExecuteConfigId
    )!;
    configTemplate = configData.configTemplate;
    startTimeUnix = dayjs().unix();
    // 会继续触发查询当前累计用户的接口
    // switchTimeData(2);
    initTimer();
    luckyBagConfigTemplate = configTemplate.find(
      (item) => item.type == "luckyBag"
    );
  }

  function start(data: any) {
    app.isExecuteConfigId = data.id;
    let configData = app.configFrom.find(
      (item) => item.id === app.isExecuteConfigId
    )!;
    configTemplate = configData.configTemplate;
    startTimeUnix = dayjs().unix();
    // 会继续触发查询当前累计用户的接口
    // switchTimeData(2);
    initTimer();

    luckyBagConfigTemplate = configTemplate.find(
      (item) => item.type == "luckyBag"
    );
  }

  function stop() {
    app.isExecuteConfigId = "";
    sendTimes = [];
    configTemplate = [];
    checkStatus = false;
    startTimeUnix = null;
    clearTimeout(timer);
    timer = null;
    isObtainStatus = true;
    luckyBagExecuteTime = 0; // 福袋执行时间
    luckyBagReleaseTime = 0; // 福袋发布时间
    luckyBagStepIndex = 0;
    currentUserCnt = 0;
    luckyBagConfigTemplate = null;
  }

  async function initTimer() {
    let jTime = dayjs().unix();
    console.log("判断1");
    // 正在处理中，不继续执行
    if (!checkStatus) {
      checkStatus = true;
      for (let key in configTemplate) {
        let item = configTemplate[key];
        let sendTime = sendTimes[key];
        // 通过当前秒数 - 开始执行任务时的秒数 和 延迟时间判断是否允许执行下方操作
        if (startTimeUnix && jTime - startTimeUnix < item.delay) {
          continue;
        }

        if (
          item.type == "shoppIngpopUp" &&
          (!sendTime || jTime - item.interval >= sendTime)
        ) {
          try {
            console.log(`弹出讲解弹框${key}`);
            if (location.href.includes("https://ark.xiaohongshu.com/")) {
              await xhsPopUpGoodsPop(item);
            } else {
              await popUpGoodsPop(item);
            }
          } catch (error) {
            notification["info"]({
              message: "运行出现报错",
              description: "运行出现报错，请刷新后重试。",
              duration: 0,
              onClick: () => {
                console.log("Notification Clicked!");
              },
            });

            stop();
            return;
          }
          sendTimes[key] = jTime;
        }
        if (
          item.type == "comment" &&
          (!sendTime || jTime - item.interval >= sendTime)
        ) {
          try {
            console.log(`发送并置顶消息${key}`);
            if (location.href.includes("https://ark.xiaohongshu.com/")) {
              await xhsSendMessage(item);
            } else {
              await sendMessageAndTop(item);
            }
          } catch (error) {
            notification["info"]({
              message: "运行出现报错",
              description: "运行出现报错，请刷新后重试。",
              duration: 0,
              onClick: () => {
                console.log("Notification Clicked!");
              },
            });
            stop();
            return;
          }

          sendTimes[key] = jTime;
        }
        console.log(
          item.type == "luckyBag" && isObtainStatus,
          'item.type == "luckyBag" && isObtainStatus'
        );

        //  福袋发布逻辑暂定每3分钟执行一次
        if (item.type == "luckyBag" && isObtainStatus) {
          // 程序每间隔3分钟才会重新触发发布福袋的实现逻辑
          if (jTime - luckyBagExecuteTime > 60 * 2) {
            console.log(
              jTime - luckyBagReleaseTime > 60 * 16,
              "jTime - luckyBagReleaseTime > 60 * 16"
            );
            // 发布福袋16分钟后才会再次执行逻辑
            if (jTime - luckyBagReleaseTime > 60 * 16) {
              luckyBagExecuteTime = jTime;
              console.log(
                currentUserCnt < item.peopleNum && luckyBagStepIndex == 0,
                currentUserCnt,
                item.peopleNum,
                luckyBagStepIndex,
                "currentUserCnt < item.peopleNum && luckyBagStepIndex == 0"
              );
              if (currentUserCnt < item.peopleNum && luckyBagStepIndex == 0) {
                luckyBagStepIndex = 1;
                openLuckyBigTool();
              }
            }
          }
        }
      }

      checkStatus = false;

      if (!app.isExecuteConfigId) return;

      timer = setTimeout(() => {
        initTimer();
      }, 1000);
    }
  }
  return {
    start,
    stop,
  };
}
